package com.zzzyh.forumsystemclient.cotroller;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.dao.UserMapper;
import com.zzzyh.forumsystemclient.model.*;
import com.zzzyh.forumsystemclient.services.INotificationService;
import com.zzzyh.forumsystemclient.services.IUserService;
import com.zzzyh.forumsystemclient.utils.IpUtil;
import com.zzzyh.forumsystemclient.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private INotificationService notificationService;

    @RequestMapping("/api/user/getUserinfo")
    public AppResult<User> getUserinfo(@RequestHeader("Authorization") String token) {
//        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
//        log.info("用户{}获取用户信息成功",user.getUsername());
//        return AppResult.success(user.getUser());
        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Integer userId = user.getUser().getId();
        User userinfo = userService.getUserinfoByUserId(userId);
        userinfo.setPassword(null);
        return AppResult.success(userinfo);
    }
    @RequestMapping("/sys/user/profile")
    public AppResult<Map<String,Object>> profile(@RequestHeader("Authorization") String token)
    {
        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Map<String,Object> map = new HashMap<>();
        map.put("sysUser",user.getUser());
        map.put("role",user.getUser().getRole());
        return AppResult.success(map);
    }
    @RequestMapping("/sys/user/updatePwd")
    public AppResult<String> updatePwd(@RequestBody PasswordRequest passwordRequest,
                                       @RequestHeader("Authorization") String token){
        // 1. 解析 token 获取当前用户
        LoginUser loginUser = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        User user = loginUser.getUser();

        // 2. 查询数据库中的原始密码
        User dbUser = userService.getUserinfoByUserId(user.getId()); // 假设 selectById 是根据用户ID查询用户的函数
        if(dbUser == null)
            return AppResult.failed("用户不存在");
        String storedPassword = dbUser.getPassword(); // 数据库中存储的加密密码
        String oldPassword = passwordRequest.getOldPassword();
        String newPassword = passwordRequest.getNewPassword();
        String confirmPassword = passwordRequest.getConfirmPassword();

        // 3. 校验旧密码是否正确
        if (!passwordEncoder.matches(oldPassword, storedPassword)) {
            return AppResult.failed("旧密码不正确");
        }

        // 4. 校验新密码与确认密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            return AppResult.failed("新密码和确认密码不一致");
        }

        // 5. 加密新密码并更新到数据库
        String encodedNewPassword = passwordEncoder.encode(newPassword);
        userService.updatePassword(encodedNewPassword, user.getId()); // 假设 updateUser 是更新用户信息的函数

        return AppResult.success("密码修改成功");
    }

    @RequestMapping("/api/usernameIsUnique")
    public AppResult<Boolean> usernameIsUnique(@RequestParam("username") String username) {
        log.info("检查用户名唯一性: " + username);
        if(userService.usernameExists(username, null)){
            return AppResult.success(false);
        }else {
            return AppResult.success(true);
        }
    }

    @RequestMapping("/user/myTalk/{userId}")
    public AppResult<List<Moment>> myTalk(@PathVariable("userId") Integer userId) {
        log.info("获取用户信息: " + userId);
        return AppResult.success(userService.myTalk(userId));
    }

    @RequestMapping("/user/delMyTalk/{talkId}")
    public AppResult<String> delMyTalk(@PathVariable("talkId") Integer talkId) {
        log.info("删除动态: " + talkId);
        userService.delMyTalk(talkId);
        return AppResult.success("删除成功");
    }

    @RequestMapping("/user/followUser/{userId}")
    public AppResult<String> followUser(@PathVariable("userId") Integer userId,
                                       @RequestHeader("Authorization") String token) {
        LoginUser loginUser = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Integer myId = loginUser.getUser().getId();
        log.info("用户{}开始关注用户{}",myId,userId);
        Integer like = userService.isFollowAuthor(myId, userId);
        if(like != null && like == 1){
//            return AppResult.failed("已关注");
            userService.unFollowUser(myId,userId);
            return AppResult.success("取消关注成功");
        }else {
            userService.followUser(myId,userId);
            Notifications notifications = new Notifications();
            notifications.setUserId(Long.valueOf(userId));
            notifications.setFromUserId(Long.valueOf(myId));
            notifications.setType("follow");
//            notifications.setTitle("关注");
            notifications.setMessage("关注了你");
            notifications.setIsRead(false);
            notifications.setCreateTime(new Date());
            User user = userService.getUserinfoByUserId(myId);
            notifications.setTitle("@"+user.getUsername()+"("+user.getNickname()+")");
            notificationService.add(notifications);
            return AppResult.success("关注成功");
        }
    }

    @RequestMapping("/user/unFollowUser/{userId}")
    public AppResult<String> unFollowUser(@PathVariable("userId") Integer userId,
                                       @RequestHeader("Authorization") String token) {
        LoginUser loginUser = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Integer myId = loginUser.getUser().getId();
        log.info("用户{}开始取消关注用户{}",myId,userId);
        Integer like = userService.isFollowAuthor(myId, userId);
        if(like == null || like == 0){
            return AppResult.success("已取关");
        }else {
            userService.unFollowUser(myId,userId);
            return AppResult.success("取关成功");
        }
    }

    @RequestMapping("/user/statistics/{userId}")
    public AppResult<Statistics> statistics(@PathVariable("userId") Integer userId) {
        log.info("获取用户信息: " + userId);
        Statistics statistics = new Statistics();
        statistics.setPosts(userService.totalPosts(userId));
        statistics.setLikes(userService.totalLikes(userId));
        statistics.setFollowers(userService.totalFollowers(userId));
        return AppResult.success(statistics);
    }



}
